package com.immoc.jdbc.sample;

import com.immoc.jdbc.common.DbUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Transaction {
    public static void main(String[] args) {
        Connection connection =null;
        PreparedStatement preparedStatement = null;
        try {
            connection = DbUtils.getConnection();
            connection.setAutoCommit(false);
            String sql = "insert into employee(eno,ename,salary,dname) values (?,?,?,?)";
            preparedStatement = connection.prepareStatement(sql);
            for(int i=100;i<200;i++){
//                if(i==5){
//                    throw new RuntimeException("插入失败");
//                }
                preparedStatement.setInt(1, i);
                preparedStatement.setString(2, i+"员工");
                preparedStatement.setFloat(3, i+1000);
                preparedStatement.setString(4, "市场部");
//                preparedStatement.executeUpdate();
                preparedStatement.addBatch();
            }
            preparedStatement.executeBatch();
            connection.commit();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            try {
                if(connection!=null && !connection.isClosed())
                connection.rollback();
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        } finally {
            DbUtils.closeConnection(connection);
        }
    }
}
